package com.atguigu.exam.service.impl;

import com.atguigu.exam.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */
@Service
@Slf4j
@EnableConfigurationProperties(MinioProperties.class)
//自动创建 MinioProperties 实例并注入到Spring容器中
//使 MinioProperties 能够从配置文件中自动绑定属性值
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String uploadFile(MultipartFile file) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    //设置Minio服务器地址
                    .endpoint(minioProperties.getEndpoint())
                    //设置用户名和密码
                    .credentials(minioProperties.getAccessKey(),minioProperties.getSecretKey())
                    .build();

            // 检查存储桶是否已经存在
            boolean isExist =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if(isExist) {
                System.out.println("Bucket "+minioProperties.getBucketName()+" already exists.");
            } else {
                //如果桶不存在则创建它
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            }

            //获取文件夹名
            String filename = file.getOriginalFilename();
            //获取上传文件夹的后缀名
            String suffix = filename.substring(filename.lastIndexOf("."));
            //使用UUID生成文件名
            String priffix = UUID.randomUUID().toString().replaceAll("-", "");
            //对当前日期格式化
            String format = DateFormatUtils.format(new Date(), "yyyy/MM/dd");
            //创建新文件夹
            String fileName = format+"/"+priffix+suffix;
            //获取输入流
            InputStream inputStream = file.getInputStream();
            //获取文件的大小
            long size = file.getSize();
            //2.创建PutObjectArgs对象
            PutObjectArgs builder = PutObjectArgs.builder()
                    //minio服务器中的桶的名字
                    .bucket(minioProperties.getBucketName())
                    //设置上传到minio服务器的文件名
                    .object(fileName)
                    //设置上传的文件流
                    .stream(inputStream, size, -1)
                    .build();
            //使用putObject上传文件到Minio服务器的桶中
            minioClient.putObject(builder);
            return minioProperties.getEndpoint()+"/"+minioProperties.getBucketName()+"/"+fileName;
        } catch (Exception e) {
            System.out.println("Error occurred:" + e);
        }
        return null;
    }
public static void main(String[] args) {
    String fileName = "ikun.gif";
    int index = fileName.lastIndexOf(".");
    System.out.println("index = " + index);
    //获取文件名的后缀
    String substring = fileName.substring(index);
    System.out.println("substring = " + substring);
    //使用UUID随机生成一个字符串作为文件名
    String uuid = UUID.randomUUID().toString();
    System.out.println("uuid = " + uuid);
}
}
